import os
import sys
import subprocess
from datetime import datetime, timedelta

def get_immediate_subdirectories(dir):
    return [name for name in os.listdir(dir) if os.path.isdir(os.path.join(dir, name))]

# The following dirs assume that all the projects and dirs are in the same main dir
baseDir = "C:\\Documents and Settings\\ajesler\\Code\\HonoursProject\\"
resultsDir = baseDir+"motif-analysis-experiment\\data" # or baseDir+"DotNet Qualitas Corpus\\Analysis"
sysDir = baseDir+"DotNet Qualitas Corpus\\Systems"
cilada = baseDir+"cilada\\v2\\cilada\\cilada\\bin\\Debug\\cilada.exe"
dependencyLibDirName = "dependencylibs"

if not os.path.exists(cilada):
	print "Could not find cildada.exe at ",cilada
	sys.exit(1)

startTime = datetime.now()

for subdir in get_immediate_subdirectories(sysDir):
    if(subdir.startswith(".svn")): continue
    
    print subdir
    fullPath = os.path.join(sysDir, subdir)
    for sysVer in get_immediate_subdirectories(fullPath):
        if(sysVer.startswith(".svn")): continue
        
        sysVerFull = os.path.join(fullPath,sysVer)
        print "\t", sysVer,

        binDir = os.path.join(sysVerFull, "bin")
        if(os.path.exists(binDir)):
            depDir = os.path.join(sysVerFull, dependencyLibDirName)

            args = [cilada, "-d "+binDir, "-o "+resultsDir, "-n "+sysVer, "-r"]
            
            if(os.path.exists(depDir)):
                args.append("-s "+depDir)

            s = datetime.now()
            result = subprocess.call(args)
            e = datetime.now()
            if not result:
                print " Completed in ",(e-s)
            else:
                print " Failed after ",(e-s)
        else:
            print "Failed - No bin directory found"
        
endTime = datetime.now()
delta = endTime - startTime
print "Analysis completed in ",delta
